﻿using System;
using System.ComponentModel;
using System.Windows.Forms;
using Barbar.UrlGuard.BL;
using Barbar.UrlGuard.Properties;
using Barbar.UrlGuard.Controls;
using Barbar.UrlGuard.Dal.Persist;
using Barbar.UrlGuard.Dal;
using System.Collections.Generic;

namespace Barbar.UrlGuard {
  public partial class FormMain : LocalizableForm, ILocalizable, ITickCallback {
    private bool m_SuspendTimer = false;

    public FormMain() {
      InitializeComponent();
    }

    private void timer_Tick(object sender, EventArgs e) {
      if (m_SuspendTimer)
        return;

      m_SuspendTimer = true;
      notifyIcon.Icon = Resources.icon_toolbar_synchronize;

      ITickService tickService = ServiceLocator.Instance.Resolve<ITickService>();
      tickService.ProcessTick(this);
    }

    private void FormMain_Load(object sender, EventArgs e) {
      if (!DesignMode) {
        chainTreeView.RedrawTree();
        chainTreeToolStrip.UpdateToolStrip(chainTreeView);
      }
    }

    protected override void OnClosing(CancelEventArgs e) {
      e.Cancel = true;
      this.Visible = false;
    }

    private void DoShowForm() {
      this.WindowState = FormWindowState.Normal;
      this.Visible = true;
      this.Focus();
    }

    private void DoShowConfiguration() {
      FormConfiguration formConfiguration = new FormConfiguration();
      formConfiguration.ShowDialog(this);
    }

    private void DoShowAbout() {
      FormAbout formAbout = new FormAbout();
      formAbout.ShowDialog(this);
    }

    private void notifyIcon_MouseDoubleClick(object sender, MouseEventArgs e) {
      DoShowForm();
    }

     private void chainTreeView_AfterSelect(object sender, TreeViewEventArgs e) {
      chainTreeToolStrip.UpdateToolStrip(chainTreeView);
    }

    private void chainTreeToolStrip_Command(object sender, ChainTreeToolStripEventArgs e) {
      switch (e.Command) {
        case ChainTreeToolStripCommand.AddChain:
          chainTreeView.AddChain();
          break;
        case ChainTreeToolStripCommand.EditChain:
          if (chainTreeView.SelectedChain != null) {
            chainTreeView.EditChain(chainTreeView.SelectedChain);
          }
          break;
        case ChainTreeToolStripCommand.AddUrl:
          if (chainTreeView.SelectedChain != null) {
            chainTreeView.AddUrl(chainTreeView.SelectedChain);
          }
          break;
        case ChainTreeToolStripCommand.EditUrl:
          if (chainTreeView.SelectedEntry != null) {
            chainTreeView.EditUrl(chainTreeView.SelectedEntry);
          }
          break;
        case ChainTreeToolStripCommand.RemoveChain:
          chainTreeView.RemoveChain(chainTreeView.SelectedChain);
          break;
        case ChainTreeToolStripCommand.RemoveUrl:
          chainTreeView.RemoveUrl(chainTreeView.SelectedEntry, chainTreeView.SelectedChain);
          break;
        default:
          throw new NotImplementedException();
      }
    }

    private void mainContextMenuStrip_Command(object sender, MainContextMenuEventArgs e) {
      switch (e.Command) {
        case MainContextMenuCommand.Exit:
          Application.Exit();
          break;
        case MainContextMenuCommand.ShowStatus:
          DoShowForm();
          break;
        case MainContextMenuCommand.ShowConfiguration:
          DoShowConfiguration();
          break;
        case MainContextMenuCommand.ShowAbout:
          DoShowAbout();
          break;
        default:
          throw new NotImplementedException();
      }
    }

    #region ILocalizable Members

    public void Localize(ILocalizator localizator) {
      if (localizator == null)
        throw new ArgumentNullException("localizator");
      mainContextMenuStrip.Localize(localizator);
      Text = localizator.Translate("FormMain_Title");
    }

    #endregion

    #region ITickCallback Members

    public void TickFinished(IEnumerable<MonitoringEntry> checkedEntries) {
      if (this.InvokeRequired) {
        this.Invoke(new TickCallback(TickFinished), checkedEntries);
        return;
      }

      IDataContextUpdator updator = ServiceLocator.Instance.Resolve<IDataContextUpdator>();
      bool isError, isNewError;
      updator.UpdateContextWithCheck(checkedEntries, out isError, out isNewError);

      IDataContextHolder dataContextHolder = ServiceLocator.Instance.Resolve<IDataContextHolder>();
      if (isError) {
        if (isNewError) {
          if (dataContextHolder.Context.UseBubbleAlert) {
            notifyIcon.ShowBalloonTip(5000, "Problem detected", "There were problem accessing at least one url.", ToolTipIcon.Error);
          }
          EmailAlertSettings alert = dataContextHolder.Context.EmailAlert;
          if (alert != null) {
            IEmailAlertService emailAlertService = ServiceLocator.Instance.Resolve<IEmailAlertService>();
            emailAlertService.SendEmailWarning(alert);
          }
        }

        notifyIcon.Icon = Resources.icon_toolbar_error;
      } else {
        notifyIcon.Icon = Resources.icon_toolbar_standby;
      }

      chainTreeView.RedrawTree();
      chainTreeToolStrip.UpdateToolStrip(chainTreeView);
      m_SuspendTimer = false;
    }

    #endregion
  }
}
